package com.yang.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.stereotype.Component;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT工具类
 */
@Component
public class JwtUtils {
    private static final Key SIGN_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS512);
    private static final Long EXPIRE = 24 * 60 * 60 * 1000L;

    /**
     * 生成JWT令牌（只包含用户名）
     */
    public static String generateToken(String username) {
        return Jwts.builder()
                .setSubject(username)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SIGN_KEY)
                .compact();
    }

    /**
     * 生成JWT令牌（包含用户名和角色码）
     */
    public static String generateTokenWithRole(String username, String roleCode) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("roleCode", roleCode);
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(username)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SIGN_KEY)
                .compact();
    }

    /**
     * 解析JWT令牌，获取用户名
     */
    public static String parseJWT(String token) {
        try {
            return Jwts.parserBuilder()
                    .setSigningKey(SIGN_KEY)
                    .build()
                    .parseClaimsJws(token)
                    .getBody()
                    .getSubject();
        } catch (Exception e) {
            throw new RuntimeException("令牌已过期");
        }
    }

    /**
     * 解析JWT令牌，获取角色码
     */
    public static String parseRoleCode(String token) {
        try {
            Claims claims = Jwts.parserBuilder()
                    .setSigningKey(SIGN_KEY)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
            return claims.get("roleCode", String.class);
        } catch (Exception e) {
            throw new RuntimeException("令牌已过期");
        }
    }
}
